import React, { useEffect, useState } from "react";
import "./index.less";
import examination from "@/assets/images/home/examination.png";
import books from "@/assets/images/home/books.png";
import practice from "@/assets/images/home/practice.png";
import { HomeApi } from "../../api/index";
import { useNavigate } from "react-router-dom";
import { Button } from "@mui/material";
import ArrowRightIcon from "@mui/icons-material/ArrowRight";
import { useSelector } from "react-redux";
import ListItem from "./components/ListItem";

export default function Home() {
  const [title, setTitle] = useState("");
  const [study, setStudy] = useState(0);
  const [total, setTotal] = useState(0);
  const [wrong, setWrong] = useState(0);
  const [collect, setCollect] = useState(0);
  const [actionCodes, setActionCodes] = useState("");
  // 请求回来的数组
  const [list, setList] = useState<IExamItem[]>([]);
  const nav = useNavigate();
  const goto = () => {
    nav("/subjects/" + actionCodes);
  };
  useEffect(() => {
    let token = localStorage.getItem("x-auth-token");
    if (!token) {
      setTimeout(() => {
        alert("还未登录,即将跳转到登录页");
        nav("/login");
      }, 2000);
      return;
    }
    HomeApi().then((res) => {
      // console.log(res.data.exemItems);
      if (res.errCode === 0) {
        setTitle(res.data.exam.title);
        setStudy(res.data.study);
        setTotal(res.data.exam.itemCount);
        setWrong(res.data.wrong);
        setCollect(res.data.collect);
        setList(res.data.exemItems);
        setActionCodes(res.data.exam.actionCode);
      }
    });
  }, []);

  return (
    <div className="home">
      <header>
        <h2>{title}</h2>
        <Button security="type" onClick={goto}>
          <span>切换考试科目</span>
          <ArrowRightIcon />
        </Button>
      </header>
      <div className="banner">
        <div className="welcome">欢迎使用IT猿题库！</div>
        <div className="learned">
          <div>已学{study}题</div>
          <div>共{total}题</div>
        </div>
        <div className="bottom">
          <section>
            <div className="num">{wrong}</div>
            <div className="txt">错题</div>
          </section>
          <section>
            <div className="num">{collect}</div>
            <div className="txt">收藏</div>
          </section>
        </div>
      </div>
      <div className="img">
        <img src={examination} alt="" />
        <img src={books} alt="" />
        <img src={practice} alt="" />
      </div>
      <div className="mytitle">
        <h2>学科题库</h2>
      </div>
      <div>
        {list.map((item) => (
          <ListItem data={item} key={item.id} />
        ))}
      </div>
    </div>
  );
}
